package com.ease.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: chenhs
 * @date: Created in 11:18 2019/12/23
 **/
public class BIOServerV3 {

    private static Charset charset = Charset.forName("UTF-8");

    public static void main(String[] args) {
        int port = 9010;
        //第4个线程阻塞等待
        int nThreads = 3;
        ExecutorService tpool = new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

        try (ServerSocket ss = new ServerSocket(port)) {
            while (true) {
                // 接收连接（阻塞-等待连接）
                Socket socket = ss.accept();
                //丢到线程池中去跑
                tpool.submit(new SocketProcess(socket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        tpool.shutdown();
    }

    static class SocketProcess implements Runnable {
        Socket socket;

        public SocketProcess(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset))) {
                String mess;
                // 读取数据（阻塞-等待数据读取）
                while ((mess = reader.readLine()) != null) {
                    System.out.println(mess);
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
